/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","jqprint","fu/app/comm/comm","fu/app/comm/validate","fu/app/comm/attention",
	"scprit/followup/app/outPatient/outPatient.ui.js",
	"scprit/followup/app/outPatient/outPatient.servers.js",
	"scprit/followup/app/question/question.ui.js",
	"scprit/followup/app/question/question.event.js"
	],function($,$bb,$jqprint,$comm,$validate,$attention,$outPatientUi,$outPatientServers,$questionUi,$questionEvent){
	var event = {};
	
	/**
	 * 刷新任务列表UI
	 */
	var refreshTasksUi = function(rows,curInfo){
		$outPatientUi.showContainerInit({
			id:"showContainer",
			list: rows,
			taskId: curInfo.taskId,  // 从随访记录中跳过来，带过来的 taskId,(目的：当前标记，背景变绿)
		});
		if(curInfo.taskId === rows[0].taskId){
			$(".show-wrapper > div.row").eq(0).addClass("active").siblings().removeClass("active");
		}
	};
	/**
	 * 点击打印按钮
	 */
	var onPrintClick = function(event){
        $("#printContent").jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
        return;
	}
	/**
	 * navbar点击左右箭头进行滚动
	 */
	var onNavbarRoll = function($arrLeft,$arrRight,$wrapper,showNum,w,len,i,W,showWidth){
		var j = 0;
		$arrLeft.unbind("click"); //先解除绑定事件,绑定新事件
		$arrLeft.click(function(){
			if( i > showNum ){
				j++;
				i--;
				$wrapper.animate({ marginLeft: -W+w*j });
			}else if(i == showNum){
				j++;
				i--;
				$wrapper.animate({ marginLeft: 0 });
			} 
		});
		$arrRight.unbind("click");
		$arrRight.click(function(){
			if( len >= showNum ){
				if( i < len-1 ){
					j--;
					i++;
					$wrapper.animate({ marginLeft: -W+w*j });
				}else if(i == len-1){
					$wrapper.animate({ marginLeft: showWidth-w*len });
				}
			}
		});
	};
	/**
	 * navbar初始化，调用点击事件
	 */
	var onNavbarRollInit = function(index){
		var $oRow = $(".show-wrapper div.row");
		var len = $oRow.length;
		var w = $oRow.eq(0).width();
		$(".show-wrapper").css( "width", w*len + 'px' );  // width根据.row的个数定义
		var showWidth = $("#showContainer").width()-13;		// 不知道为什么会有13px的差距
		var showNum = Math.round( showWidth / w );
		var W = w*(index+1)-showWidth;
		if(index >= showNum){
			$(".show-wrapper").css({ marginLeft: -W });
		}
		onNavbarRoll($(".arrow-left"),$(".arrow-right"),$(".show-wrapper"),showNum,w,len,index,W,showWidth);
	}

	/**
	 * 请求患者基本信息成功后的回调函数
	 */
	var getRevisedInfoParamsCallback = function(data,params,curInfo){
		params.patientName = data.PatientInfo.userName;
		params.imgSrc = "page/followup/imgs/comm/" + ( data.PatientInfo.gender == "F" ? "girl":"boy" ) + ".png";
		params.gender = data.PatientInfo.gender;
		params.taskId = curInfo.taskId;
		$outPatientServers.ajaxTasks(getTasksCallback,params);
    	$bb.toastShow("保存成功！",3000);
	}
	/**
	 * 保存问卷成功后的回调方法
	 */
	var getSaveCallback = function(params,curInfo){
		$outPatientServers.getRevisedInfoParams(params,curInfo,getRevisedInfoParamsCallback);
	}
	/**
	 * 保存随访问卷答案
	 */
	var onSaveQuestion = function(){
		if( $validate.init() ){
			var data = $(this).data("params");
			$outPatientServers.ajaxSaveQuestion(data.data,data.params,data.curInfo,getSaveCallback);
		}
	}
	/**
	 * 请求医院的信息成功后的回调函数(打印时需要)
	 */
	var handlePrintHospitalCallBack = function(hospital,info,data){
		$outPatientUi.printInit({
        	"id":"printContent",
        	"info":info,
        	"data":data,
        	"hospital":hospital
        });
	}
	/**
	 * 根据患者id请求患者基本信息成功后的回调函数(打印时需要)
	 */
	var getPatientInfoByPtIdCallBack = function(info,data){
		$outPatientServers.handlePrintHospital(info,data,handlePrintHospitalCallBack)
	}
	/**
	 * 改变随访日期时，年龄随之改变
	 */
	var changeAgeByFinishDate = function(){
		var time = $(this).val();
    	var birthday = $("#followupAge").attr("birthday");
    	var expectedDay = $("#followupAge").attr("expectedDay");
    	var pregnancyDay = $("#followupAge").attr("pregnancyDay");
    	var paramsAge = {
    		"birthday":birthday,
    		"expectedDay":expectedDay,
    		"pregnancyDay":pregnancyDay
    	}
    	var followupAge = $outPatientServers.getFollowupAge(paramsAge,time);
    	$("#followupAge .control-label").html(followupAge.ageLabel);
    	$("#followupAge p[name=followupAge]").html(followupAge.age);
    	if( $("#followupActualAge").length > 0 && followupAge.actualAgeLabel && followupAge.actualAge ){
    		$("#followupActualAge .control-label").html(followupAge.actualAgeLabel);
    		$("#followupActualAge p[name=followupActualAge]").html(followupAge.actualAge);
    	}
	}
	/**
	 * 锚点事件
	 */
	var anchorMenuEvent = function(){
		$("#anchorMenu .anchor-menu-fold").click(function(){
        	$("#anchorMenu .anchor-menu-unfold").show();
        	$("#anchorMenu .anchor-menu-fold").hide();
        });
        $("#anchorMenu .anchor-menu-unfold .anchor-menu-close").click(function(){
        	$("#anchorMenu .anchor-menu-fold").show();
        	$("#anchorMenu .anchor-menu-unfold").hide();
        });
        $("#anchorMenu .anchor-menu-unfold ul li").click(function(){
        	$(this).addClass("active").siblings().removeClass("active");
        });
		var obj = document.getElementById("content-main");   
		if( obj.scrollHeight > obj.clientHeight || obj.offsetHeight > obj.clientHeight){ 
			$("#anchorMenu").css({"right":"27px"});
		}else{
			$("#anchorMenu").css({"right":"20px"});
		}
	}
	/**
	 * 请求问卷成功后的回调方法
	 */
	var getQuestionCallback = function(data,params,curInfo,addTaskInfo){
		/* 打印 */
        $outPatientServers.getPatientInfoByPtId(params,data,getPatientInfoByPtIdCallBack);
		$outPatientUi.followUpInit({
        	id: "followUpInfo",
        	list: data.questiones,	  // 问卷
            status: curInfo.status,
            task: data.task,	 // 随访指导
            ageRelate:params,	// 随访指导里的随访年龄相关数据
            sampleList:data.sampleList
        });
        /* 改变随访日期时，年龄随之改变 begin */
        $("input[name=finishDate]").unbind("change");
        $("input[name=finishDate]").change(changeAgeByFinishDate);
        /* end 改变随访日期时，年龄随之改变 */
        $questionUi.init({
        	id: "questions",
        	status: curInfo.status,
            list: data.questiones,	  // 问卷
            values: data.values,	// 问卷答案
        });
        $questionEvent.init({
        	"getGrowth":{
        		"patientId":data.oprInfo.patientId,
	        	"preTaskId":curInfo.preTaskId,
	        	"followQueueId":params.followQueueId,
            	"gender":params.gender
        	},
        	"getTextareaAssess":{
        		"userId":params.patientId,
        		"taskId":curInfo.taskId
        	}
        });
        $outPatientUi.anchorMenuInit({
        	"id":"anchorMenu",
        	"list":data.questiones
        });
        // 锚点事件
        anchorMenuEvent();
        $attention.init();
        $('.validatebox').data("attentionFun",$attention.blurInit);	// 校验之前提示警告
        $validate.blurInit();
		var params01 = {
			status: curInfo.status,
			seqNo: curInfo.seqNo,
			taskStatus:curInfo.taskStatus,
			addTaskFlag:addTaskInfo.addTaskFlag
		};
		var params02 = {
			callback1:onPatientDelect,
			callback2:onSaveQuestion,
			callback3:onChangeCanWrite,
			callback4:onAddTask,
			callback5:onPrintClick,
			params1:$outPatientServers.getDeleteParams(),
			params2:{data:data,params:params,curInfo:curInfo},
			params3:{data:data,params:params,curInfo:curInfo,addTaskInfo:addTaskInfo},
			params4:{params:params,afterTaskId:addTaskInfo.afterTaskId,fun:$outPatientServers.ajaxTasks,getTasksCallback:getTasksCallback},
		};
		var topbars = $outPatientServers.handleBtnGroup(params01,params02);
		$bb.toolbar(topbars);
	}
	var onAddTask = function(){
		var data = $(this).data("params");
		$bb.toastConfirmShow($outPatientServers.ajaxAddTask,data,"确定添加临时随访?");
	}
	/**
	 * 点击修改按钮将问卷转化为可写状态
	 */
	var onChangeCanWrite = function(){
		var data = $(this).data("params");
    	data.curInfo.status = "default";
		getQuestionCallback(data.data,data.params,data.curInfo,data.addTaskInfo);
	}
	/**
	 * 切换随访任务
	 */	
	var onTaskSelect = function(){
		var data = $(this).data();
		var curInfo = data.curInfo;
		var params = data.params;
		if(data.flag){ // 判断是否是点击taskBabycard过来的
			$(".show-wrapper > div.row").eq(0).addClass("active").siblings().removeClass("active");
			$(".show-wrapper").css({"marginLeft":0});
			var obj = data.rows[0];
			curInfo.taskId = obj.taskId;
			curInfo.taskStatus = obj.taskStatus;
			curInfo.status = $outPatientServers.curTaskStatus( obj.taskStatus );
			curInfo.seqNo = obj.seqNo;
			curInfo.preTaskId = "";
		}else{
			$(this).addClass("active").siblings().removeClass("active");
			curInfo.taskId = $(this).attr("taskid");
			curInfo.taskStatus = $(this).attr("taskstatus");
			curInfo.status = $outPatientServers.curTaskStatus( $(this).attr("taskstatus") );
			curInfo.seqNo = $(this).attr("seqno");
			curInfo.preTaskId = $(this).attr("preTaskId");
		}
		$outPatientServers.ajaxQuestion(params,curInfo,getQuestionCallback,data.addTaskInfo);
	}
	/**
	 * 请求任务列表成功后的回调方法
	 */
	var getTasksCallback = function(rows,params){
		$outPatientUi.taskBabycardInit({	// 个人信息
			id:"taskBabycard",
			list: params,
		});
		var curInfo = $outPatientServers.getCurInfo(rows,params.taskId);
		refreshTasksUi(rows,curInfo);
		var addTaskInfo = $outPatientServers.getAddTaskInfo(rows);	// 添加临时随访
		var index = $outPatientServers.getTaskIndexByTaskId(rows,curInfo.taskId);
		onNavbarRollInit(index);
		$outPatientServers.ajaxQuestion(params,curInfo,getQuestionCallback,addTaskInfo);
		$(".show-wrapper > div.row").data({curInfo: curInfo, params :params, addTaskInfo:addTaskInfo});
		$(".show-wrapper > div.row").click(onTaskSelect);
		// 点击taskBabycard跳转到建档（此页面的建档）
		$("#taskBabycard").unbind("click");
		$("#taskBabycard").data({flag:true, rows: rows, curInfo: curInfo, params :params, addTaskInfo:addTaskInfo});
		$("#taskBabycard").click(onTaskSelect);
	};
	event.getTasksCallback = function(rows,params){
		getTasksCallback(rows,params);
	};
	/**
	 * 删除患者
	 */
	var onPatientDelect = function(){
		var params = $(this).data("params");
		$bb.toastConfirmShow($outPatientServers.ajaxDelPatient,params,"确定从该队列中删除患者?");
	}
	event.onPatientDelect = function(){
		onPatientDelect();
	}
	
	return event;
});